package school30.io.memory;

import java.util.Enumeration;
import java.util.Hashtable;
import school30.io.File;

public class MemoryFileStorage {

    Hashtable h = new Hashtable();

    public Hashtable pathTable(File path) {
        Hashtable c = h;
        while (path.pathLength() > 0)
        {
            String d = (String) path.path.elementAt(0);
            path = path.removeFirst();
            c = (Hashtable) c.get(d);
        }
        return c;
    }

    public void saveFile(byte[] b, File path) {
        String fn = path.name();
        Hashtable prt = pathTable(path.getParent());
        prt.remove(fn);
        prt.put(fn, b);
    }

    public void deleteFile(File path) {
        String fn = path.name();
        Hashtable prt = pathTable(path.getParent());
        prt.remove(fn);
    }

    public byte[] readFile(File path) {
        String fn = path.name();
        Hashtable prt = pathTable(path.getParent());
        return (byte[]) prt.get(fn);
    }

    public String[] folderContent(File path) {
        Hashtable prt = pathTable(path);
        String[] mm = new String[prt.size()];
        Enumeration e = prt.keys();
        int i = 0;
        while (e.hasMoreElements()) {
            mm[i] = (String) e.nextElement();
            i++;
        }
        return mm;
    }

   public void createFolder(File path) {
        String fn = path.name();
        Hashtable prt = pathTable(path.getParent());
        prt.put(fn, new Hashtable());
    }

   public long size(File path)
   {
       String fn = path.name();
       Hashtable prt = pathTable(path.getParent());
       Object obj = prt.get(fn);
       if (obj instanceof Hashtable)
           return -2;
       else return((byte[]) prt.get(fn)).length;
   }
}
